import { defineStore } from 'pinia'
import {ref,computed} from 'vue'
export const useCounterStore = defineStore('counter', () => {
  const cartList =ref([])

   const myOrderList=ref([])

  const addItem =(playload)=>{
      const index = cartList.value.findIndex(item=>item.id==playload.id)
      if(index>-1)
      {
         cartList.value[index].count++
      }else{
        cartList.value.push({
            ...playload,
            count:1,
            checked:false
        })
      }
  }

  
  const delItem =(id)=>{
    cartList.value=cartList.value.filter(item=>item.id != id)
  }
 

  const totalCount=computed(()=>{
       let res =0 
       cartList.value.forEach(item=>{
         res +=item.count
       })
       return res
  })
   const totalPrice=computed(()=>{
       let res =0 
       cartList.value.forEach(item=>{
        if(item.checked==true)
        {
          res +=item.count*item.price
        }
        
       })
       return res.toFixed(2)
  })

  const orderList =computed(()=>{
    return cartList.value.filter(item=>item.checked==true)
  })
  const addOrderList =(payload)=>{
      myOrderList.value.push(payload)
  }
  return { cartList,addItem,delItem,totalCount,totalPrice,myOrderList,orderList,addOrderList }
},{
    persist:true
})